<template>
  <div class="level-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>会员等级管理</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleAdd">新增等级</el-button>
          </div>
        </div>
      </template>

      <!-- 等级列表 -->
      <el-table
        v-loading="loading"
        :data="levelList"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="name" label="等级名称" width="120" />
        <el-table-column prop="code" label="等级代码" width="120" />
        <el-table-column prop="icon" label="等级图标" width="100">
          <template #default="{ row }">
            <el-image
              v-if="row.icon"
              :src="row.icon"
              :preview-src-list="[row.icon]"
              fit="contain"
              style="width: 40px; height: 40px"
            />
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="minPoints" label="所需积分" width="100" />
        <el-table-column prop="discount" label="折扣率" width="100">
          <template #default="{ row }">
            {{ row.discount }}%
          </template>
        </el-table-column>
        <el-table-column prop="description" label="等级说明" />
        <el-table-column prop="memberCount" label="会员数量" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="success"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(row)"
              :disabled="row.memberCount > 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑等级对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增等级' : '编辑等级'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="等级名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入等级名称" />
        </el-form-item>
        <el-form-item label="等级代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入等级代码" />
        </el-form-item>
        <el-form-item label="等级图标" prop="icon">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.icon" :src="form.icon" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="所需积分" prop="minPoints">
          <el-input-number
            v-model="form.minPoints"
            :min="0"
            :precision="0"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="折扣率" prop="discount">
          <el-input-number
            v-model="form.discount"
            :min="0"
            :max="100"
            :precision="0"
            style="width: 200px"
          />
          <span class="unit">%</span>
        </el-form-item>
        <el-form-item label="等级说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入等级说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 等级详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="等级详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="等级名称">{{ detail.name }}</el-descriptions-item>
        <el-descriptions-item label="等级代码">{{ detail.code }}</el-descriptions-item>
        <el-descriptions-item label="等级图标">
          <el-image
            v-if="detail.icon"
            :src="detail.icon"
            :preview-src-list="[detail.icon]"
            fit="contain"
            style="width: 60px; height: 60px"
          />
          <span v-else>无</span>
        </el-descriptions-item>
        <el-descriptions-item label="所需积分">{{ detail.minPoints }}</el-descriptions-item>
        <el-descriptions-item label="折扣率">{{ detail.discount }}%</el-descriptions-item>
        <el-descriptions-item label="会员数量">{{ detail.memberCount }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="等级说明" :span="2">{{ detail.description }}</el-descriptions-item>
      </el-descriptions>

      <!-- 会员列表 -->
      <div class="detail-section">
        <div class="section-title">会员列表</div>
        <el-table :data="detail.members" border>
          <el-table-column prop="memberNo" label="会员号" width="120" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="phone" label="手机号" width="120" />
          <el-table-column prop="points" label="积分" width="100" />
          <el-table-column prop="balance" label="余额" width="120">
            <template #default="{ row }">
              ¥ {{ row.balance?.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="registerTime" label="注册时间" width="180" />
          <el-table-column prop="lastLoginTime" label="最后登录" width="180" />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getMemberLevelList, addMemberLevel, updateMemberLevel, deleteMemberLevel } from '@/api/member'

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})

// 上传地址
const uploadUrl = import.meta.env.VITE_API_URL + '/upload'

// 表格数据
const loading = ref(false)
const levelList = ref([])
const total = ref(0)

// 新增/编辑对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = ref({
  name: '',
  code: '',
  icon: '',
  minPoints: 0,
  discount: 100,
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入等级名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入等级代码', trigger: 'blur' }
  ],
  minPoints: [
    { required: true, message: '请输入所需积分', trigger: 'blur' }
  ],
  discount: [
    { required: true, message: '请输入折扣率', trigger: 'blur' }
  ]
}

// 详情对话框
const detailDialogVisible = ref(false)
const detail = ref({})

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getMemberLevelList(queryParams.value)
    levelList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取等级列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 新增按钮点击
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    name: '',
    code: '',
    icon: '',
    minPoints: 0,
    discount: 100,
    description: ''
  }
  dialogVisible.value = true
}

// 编辑按钮点击
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = {
    id: row.id,
    name: row.name,
    code: row.code,
    icon: row.icon,
    minPoints: row.minPoints,
    discount: row.discount,
    description: row.description
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addMemberLevel(form.value)
          ElMessage.success('新增成功')
        } else {
          await updateMemberLevel(form.value.id, form.value)
          ElMessage.success('编辑成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error(dialogType.value === 'add' ? '新增失败:' : '编辑失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '新增失败' : '编辑失败')
      }
    }
  })
}

// 查看按钮点击
const handleView = (row) => {
  detail.value = row
  detailDialogVisible.value = true
}

// 删除按钮点击
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该等级吗？', '提示', {
      type: 'warning'
    })
    
    await deleteMemberLevel(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    form.value.icon = res.data.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error('上传失败')
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.level-container {
  padding: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .dialog-footer {
    text-align: right;
  }
  
  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      
      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
  }
  
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  
  .unit {
    margin-left: 10px;
    color: #909399;
  }
  
  .detail-section {
    margin-top: 20px;
    
    .section-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #303133;
    }
  }
}
</style> 